package org.fixies.spreadsheet.interpreter;

import org.fixies.spreadsheet.Book;
import org.fixies.spreadsheet.Sheet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * ブックノード
 *
 * @author Kawasaki
 */
public class BookNode {

    // TODO 無視可能なシート対処
    /**
     * 無視可能なシート名の正規表現
     */
    private static final String[] IGNORABLE_SHEET_REG_EXP = {
            "testcase", "^_.*"};

    private final String bookName_;

    public BookNode(String bookName) {
        bookName_ = bookName;
    }

    private List<SheetNode> sheetNodes_ = new ArrayList<SheetNode>();

    public void evaluate(BookContext bookContext) {

        SheetContext sheetContext;
        while (bookContext.hasNext()) {
            sheetContext = bookContext.next();

            // TODO 関係ないシートを読まない緊急対処
            if (isIgnorableSheet(sheetContext.getSheetName())) {
                continue;
            }

            // シート名がほしい
            SheetNode sheetNode = new SheetNode(bookName_, sheetContext.getSheetName());
            sheetNode.evaluate(sheetContext);

            sheetNodes_.add(sheetNode);
        }
    }

    public Book getResult() {

        Map<String, Sheet> sheets = new HashMap<String, Sheet>();
        for (SheetNode sheetNode : sheetNodes_) {
            sheets.put(sheetNode.getSheetName(), sheetNode.getResult());
        }
        return createBook(bookName_, sheets);
    }

    protected boolean isIgnorableSheet(String sheetName) {

        if (sheetName == null || sheetName.length() == 0) {
            return true;
        }
        for (String ignorableSheetRegExp : IGNORABLE_SHEET_REG_EXP) {
            if (sheetName.matches(ignorableSheetRegExp)) {
                return true;
            }
        }
        return false;
    }

    protected Book createBook(String bookName, Map<String, Sheet> sheets) {
        return new Book(bookName, sheets);
    }

}
